import type { LinkItem, OrderItem, CommissionRecord, Product } from '@/types/distributor'

// 生成随机ID
const generateId = () => Math.random().toString(36).substring(2, 12)

// 生成随机日期（当前日期前n天内的随机日期）
const generateRandomDate = (days: number) => {
  const date = new Date()
  date.setDate(date.getDate() - Math.floor(Math.random() * days))
  return date.toISOString()
}

// 生成随机金额（最小值到最大值之间）
const generateRandomAmount = (min: number, max: number) => {
  return +(Math.random() * (max - min) + min).toFixed(2)
}

// 随机选择数组中的一个元素
const randomChoice = <T>(arr: T[]): T => {
  return arr[Math.floor(Math.random() * arr.length)]
}

// 生成经销商控制台数据
export const generateDashboardData = () => {
  return {
    todayOrderCount: Math.floor(Math.random() * 15) + 1,
    todaySalesAmount: generateRandomAmount(500, 3000),
    monthlyAccumulatedCommission: generateRandomAmount(2000, 10000),
    pendingWithdrawalCommission: generateRandomAmount(800, 5000),
    activePaymentLinkCount: Math.floor(Math.random() * 25) + 5,
    orderCompletionRate: +(Math.random() * 40 + 60).toFixed(1), // 60%-100%
    weeklyGrowthRate: +(Math.random() * 40 - 20).toFixed(1), // -20% 到 +20%
    customerSatisfactionRate: +(Math.random() * 15 + 85).toFixed(1), // 85%-100%
    totalCustomers: Math.floor(Math.random() * 200) + 50,
    paymentSuccessRate: +(Math.random() * 15 + 85).toFixed(1) // 85%-100%
  }
}

/**
 * 模拟数据生成工具
 * 用于生成前端开发和测试所需的各类数据
 */

/**
 * 生成随机整数
 * @param min 最小值
 * @param max 最大值
 * @returns 随机整数
 */
function randomInt(min: number, max: number): number {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * 生成随机浮点数
 * @param min 最小值
 * @param max 最大值
 * @param decimals 小数位数
 * @returns 随机浮点数
 */
function randomFloat(min: number, max: number, decimals: number = 2): number {
  const value = Math.random() * (max - min) + min;
  return parseFloat(value.toFixed(decimals));
}

/**
 * 生成销售趋势数据
 * @param days 天数
 * @returns 销售趋势数据数组
 */
export function generateSalesTrendData(days: number = 30) {
  const result = [];
  const today = new Date();
  
  // 佣金率（假设为销售额的5-15%）
  const commissionRate = randomFloat(5, 15);
  
  // 生成每天的数据
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(date.getDate() - i);
    
    // 格式化日期为YYYY-MM-DD格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    
    // 生成销售额（模拟工作日销售额较高，周末较低的模式）
    const dayOfWeek = date.getDay(); // 0是周日，6是周六
    const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
    
    // 销售额基准范围
    const salesBase = isWeekend ? 
      randomInt(500, 2000) : // 周末
      randomInt(1000, 5000); // 工作日
    
    // 添加一些随机波动
    const sales = salesBase + randomInt(-500, 500);
    
    // 订单数（销售额的1/50到1/100，至少1个）
    const orders = Math.max(1, Math.round(sales / randomInt(50, 100)));
    
    // 佣金（销售额 * 佣金率 / 100）
    const commission = sales * commissionRate / 100;
    
    result.push({
      date: formattedDate,
      sales,
      orders,
      commission
    });
  }
  
  return result;
}

/**
 * 生成佣金数据
 * @param count 记录数量
 * @returns 佣金记录数组
 */
export function generateCommissionData(count: number = 20) {
  const result = [];
  const today = new Date();
  
  const commissionTypes = ['订单佣金', '推荐佣金', '团队佣金'];
  const statusTypes = ['已发放', '待发放', '发放中'];
  
  for (let i = 0; i < count; i++) {
    const date = new Date(today);
    date.setDate(date.getDate() - randomInt(0, 60));
    
    // 格式化日期
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(randomInt(8, 22)).padStart(2, '0');
    const minute = String(randomInt(0, 59)).padStart(2, '0');
    const second = String(randomInt(0, 59)).padStart(2, '0');
    
    const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    
    // 佣金类型
    const commissionType = commissionTypes[randomInt(0, commissionTypes.length - 1)];
    
    // 佣金金额
    let amount;
    if (commissionType === '订单佣金') {
      amount = randomFloat(10, 500);
    } else if (commissionType === '推荐佣金') {
      amount = randomFloat(5, 100);
    } else {
      amount = randomFloat(20, 1000);
    }
    
    // 订单ID（如果是订单佣金）
    const orderId = commissionType === '订单佣金' ? `ORD${randomInt(100000, 999999)}` : null;
    
    // 推荐用户（如果是推荐佣金）
    const referredUser = commissionType === '推荐佣金' ? `用户${randomInt(1000, 9999)}` : null;
    
    // 状态
    const status = statusTypes[randomInt(0, statusTypes.length - 1)];
    
    result.push({
      id: `COMM${i + 1}`,
      date: formattedDate,
      type: commissionType,
      amount,
      orderId,
      referredUser,
      status
    });
  }
  
  // 按时间降序排序
  result.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  
  return result;
}

/**
 * 生成分销商概览数据
 * @returns 分销商概览数据
 */
export function generateDistributorOverview() {
  return {
    totalSales: Math.round(150000 + Math.random() * 50000),
    totalOrders: Math.round(2200 + Math.random() * 800),
    totalCommission: Math.round(22000 + Math.random() * 8000),
    pendingCommission: Math.round(5000 + Math.random() * 3000),
    availableCommission: Math.round(8000 + Math.random() * 4000),
    conversionRate: (15 + Math.random() * 10).toFixed(2),
    activeCustomers: Math.round(180 + Math.random() * 120)
  };
}

/**
 * 生成热门商品数据
 * @param count 需要生成的商品数量
 * @returns 热门商品数据数组
 */
export function generateTopProducts(count: number = 5) {
  const products = [
    { name: '香辣鸡腿堡', category: '汉堡', image: '/assets/images/products/burger.jpg' },
    { name: '双层芝士牛肉堡', category: '汉堡', image: '/assets/images/products/cheeseburger.jpg' },
    { name: '炸鸡全家桶', category: '炸鸡', image: '/assets/images/products/chicken.jpg' },
    { name: '薯条(大)', category: '小吃', image: '/assets/images/products/fries.jpg' },
    { name: '冰淇淋甜筒', category: '甜品', image: '/assets/images/products/icecream.jpg' },
    { name: '可乐(中)', category: '饮料', image: '/assets/images/products/cola.jpg' },
    { name: '奶茶', category: '饮料', image: '/assets/images/products/milktea.jpg' },
    { name: '沙拉', category: '健康食品', image: '/assets/images/products/salad.jpg' }
  ];
  
  const result = [];
  
  // 生成销量数据并排序
  for (let i = 0; i < Math.min(count, products.length); i++) {
    const sales = Math.round(500 + Math.random() * 2000);
    const commissionRate = (10 + Math.random() * 5).toFixed(1);
    const commission = (sales * parseFloat(commissionRate) / 100).toFixed(2);
    
    result.push({
      ...products[i],
      sales,
      commission: parseFloat(commission),
      commissionRate: `${commissionRate}%`
    });
  }
  
  // 按销量排序
  return result.sort((a, b) => b.sales - a.sales);
}

/**
 * 生成最近订单数据
 * @param count 需要生成的订单数量
 * @returns 最近订单数据数组
 */
export function generateRecentOrders(count: number = 10) {
  const statuses = ['已完成', '配送中', '已付款', '已取消'];
  const customers = [
    '张先生', '李女士', '王先生', '刘女士', '陈先生', 
    '杨女士', '赵先生', '周女士', '吴先生', '郑女士'
  ];
  
  const orders = [];
  const today = new Date();
  
  for (let i = 0; i < count; i++) {
    const orderDate = new Date(today);
    // 随机生成过去7天内的订单
    orderDate.setDate(today.getDate() - Math.floor(Math.random() * 7));
    orderDate.setHours(
      Math.floor(Math.random() * 24),
      Math.floor(Math.random() * 60),
      Math.floor(Math.random() * 60)
    );
    
    const orderAmount = Math.round((50 + Math.random() * 200) * 100) / 100;
    const commissionRate = 0.1 + Math.random() * 0.1; // 10-20%的佣金率
    
    orders.push({
      id: `ORD${100000 + i}`,
      customer: customers[Math.floor(Math.random() * customers.length)],
      date: orderDate.toISOString(),
      amount: orderAmount,
      commission: parseFloat((orderAmount * commissionRate).toFixed(2)),
      status: statuses[Math.floor(Math.random() * statuses.length)],
      items: Math.floor(1 + Math.random() * 5)
    });
  }
  
  // 按日期降序排序
  return orders.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
}

/**
 * 生成热门商品排行数据
 * @param count 需要生成的商品数量
 * @returns 热门商品排行数据数组
 */
export const generateHotProductsData = generateTopProducts;

/**
 * 生成产品管理数据
 * @param count 需要生成的商品数量
 * @returns 产品管理数据数组
 */
export function generateProductsData(count: number = 50) {
  // 产品数据示例
  const products = [];
  const categories = ['汉堡', '炸鸡', '披萨', '面食', '米饭', '沙拉', '甜点', '饮料'];
  const productNames = [
    '香辣鸡腿堡', '双层芝士汉堡', '巨无霸', '麦辣鸡翅', '麦乐鸡', 
    '意式肉酱面', '泰式冬阴功汤', '日式拉面', '韩式石锅拌饭', '扬州炒饭',
    '水果沙拉', '提拉米苏', '黑森林蛋糕', '草莓冰淇淋', '可乐', '柠檬茶'
  ];
  
  for (let i = 0; i < count; i++) {
    const price = generateRandomAmount(10, 100);
    const salesVolume = Math.floor(Math.random() * 500) + 10; // 随机销量
    const commissionRate = +(10 + Math.random() * 10).toFixed(1); // 10%-20%的佣金率
    const hasDiscount = Math.random() > 0.5;
    const discountPrice = hasDiscount ? +(price * (1 - Math.random() * 0.3)).toFixed(2) : null;
    
    // 计算累计销售额和佣金
    const totalSales = price * salesVolume;
    const totalCommission = discountPrice 
      ? ((price - discountPrice) * salesVolume * (commissionRate / 100)) 
      : 0;
    
    products.push({
      id: generateId(),
      name: randomChoice(productNames),
      price,
      minPrice: +(price * 0.7).toFixed(2), // 最低折扣价
      description: '美味可口，回味无穷',
      category: randomChoice(categories),
      image: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`,
      rating: +(Math.random() * 2 + 3).toFixed(1), // 3-5星
      reviewCount: Math.floor(Math.random() * 500),
      restaurant: {
        id: generateId(),
        name: randomChoice(['麦当劳', '肯德基', '必胜客', '真功夫', '味千拉面', '星巴克'])
      },
      isCustomerFavorite: Math.random() > 0.7,
      isHot: Math.random() > 0.7,
      currentDiscount: discountPrice,
      salesVolume,
      commissionRate: `${commissionRate}%`,
      totalSales: +totalSales.toFixed(2),
      totalCommission: +totalCommission.toFixed(2),
      status: Math.random() > 0.2 ? 'active' : 'inactive', // 80%的几率是激活状态
      discount: discountPrice 
        ? +((price - discountPrice) / price * 100).toFixed(0)
        : 0, // 折扣百分比
      inventory: Math.floor(Math.random() * 100) + 5, // 库存
      lastUpdated: generateRandomDate(30) // 最后更新时间
    });
  }
  
  return products;
} 

/**
 * 生成支付链接数据
 * @param count 需要生成的链接数量
 * @returns 支付链接数据数组
 */
export function generatePaymentLinksData(count: number = 20) {
  const restaurantNames = ['麦当劳', '肯德基', '必胜客', '真功夫', '味千拉面', '星巴克'];
  const productNames = [
    '香辣鸡腿堡', '双层芝士汉堡', '巨无霸', '麦辣鸡翅', 
    '意式肉酱面', '泰式冬阴功汤', '日式拉面', '韩式石锅拌饭',
    '水果沙拉', '提拉米苏', '黑森林蛋糕', '草莓冰淇淋'
  ];
  const names = ['小明', '小红', '小刚', '小丽', '小华', '小张', '小李', '小赵'];
  const statuses = ['active', 'inactive'];
  
  return Array(count).fill(0).map((_, index) => {
    const originalPrice = generateRandomAmount(20, 100);
    const discountPrice = +(originalPrice * (1 - Math.random() * 0.3)).toFixed(2);
    const commission = +((originalPrice - discountPrice) * 0.7).toFixed(2);
    const createdDate = generateRandomDate(30);
    const createdDateObj = new Date(createdDate);
    
    // 计算过期日期 (创建日期后10-30天)
    const expiryDays = Math.floor(Math.random() * 20) + 10;
    const expiryDate = new Date(createdDateObj);
    expiryDate.setDate(expiryDate.getDate() + expiryDays);
    
    // 随机状态，但权重不同
    const status = Math.random() > 0.3 ? 'active' : 'inactive';
    
    // 生成唯一的链接ID
    const linkId = `LINK-${Date.now().toString().slice(-6)}-${index}`;
    
    // 随机使用次数，活跃链接使用次数更高
    const usageCount = status === 'active' 
      ? Math.floor(Math.random() * 20) 
      : Math.floor(Math.random() * 5);
    
    return {
      id: linkId,
      name: `给${randomChoice(names)}的美食`,
      productId: generateId(),
      productName: randomChoice(productNames),
      restaurantName: randomChoice(restaurantNames),
      productImage: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`,
      originalPrice,
      discountPrice,
      commission,
      createdAt: createdDate,
      expiresAt: expiryDate.toISOString(),
      status,
      usageCount,
      isActive: status === 'active',
      url: `https://example.com/payment/${linkId}`
    };
  });
}

/**
 * 生成链接详情数据
 * @param linkId 链接ID
 * @returns 链接详情数据
 */
export function generateLinkDetailData(linkId: string) {
  // 基础信息使用随机生成
  const originalPrice = generateRandomAmount(20, 100);
  const discountPrice = +(originalPrice * (1 - Math.random() * 0.3)).toFixed(2);
  const commission = +((originalPrice - discountPrice) * 0.7).toFixed(2);
  const createdDate = generateRandomDate(30);
  const createdDateObj = new Date(createdDate);
  
  // 计算过期日期 (创建日期后10-30天)
  const expiryDays = Math.floor(Math.random() * 20) + 10;
  const expiryDate = new Date(createdDateObj);
  expiryDate.setDate(expiryDate.getDate() + expiryDays);
  
  // 随机状态，但权重不同
  const isActive = Math.random() > 0.3;
  const status = isActive ? 'active' : 'inactive';
  
  // 访问数据
  const visits = Math.floor(Math.random() * 200) + 50;
  const conversions = Math.floor(Math.random() * visits * 0.5) + 1;
  const conversionRate = +(conversions / visits * 100).toFixed(1);
  
  // 总销售额和总佣金
  const totalSales = +(discountPrice * conversions).toFixed(2);
  const totalCommission = +(commission * conversions).toFixed(2);
  
  // 生成历史记录
  const historyRecords = generateLinkHistoryRecords(linkId, conversions);
  
  return {
    id: linkId,
    name: `给${randomChoice(['小明', '小红', '小刚', '小丽', '小华', '小张', '小李', '小赵'])}的美食`,
    productId: generateId(),
    productName: randomChoice([
      '香辣鸡腿堡', '双层芝士汉堡', '巨无霸', '麦辣鸡翅', 
      '意式肉酱面', '泰式冬阴功汤', '日式拉面', '韩式石锅拌饭',
      '水果沙拉', '提拉米苏', '黑森林蛋糕', '草莓冰淇淋'
    ]),
    restaurantName: randomChoice(['麦当劳', '肯德基', '必胜客', '真功夫', '味千拉面', '星巴克']),
    productImage: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`,
    originalPrice,
    discountPrice,
    commission,
    createdAt: createdDate,
    expiresAt: expiryDate.toISOString(),
    status,
    isActive,
    url: `https://example.com/payment/${linkId}`,
    qrCodeUrl: `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://example.com/payment/${linkId}`,
    
    // 统计数据
    visits,
    conversions,
    conversionRate,
    totalSales,
    totalCommission,
    
    // 历史记录
    historyRecords
  };
}

/**
 * 生成链接历史记录
 * @param linkId 链接ID
 * @param count 记录数量
 * @returns 历史记录数组
 */
function generateLinkHistoryRecords(linkId: string, count: number) {
  const records = [];
  const today = new Date();
  const customers = ['张先生', '李女士', '王先生', '刘女士', '陈先生', '杨女士', '赵先生', '周女士'];
  const paymentMethods = ['PayPal', 'Visa', 'MasterCard', 'UnionPay'];
  const areas = ['北京', '上海', '广州', '深圳', '杭州', '成都', '重庆', '武汉'];
  
  for (let i = 0; i < count; i++) {
    const useDate = new Date(today);
    // 随机设置日期和时间，最远不超过30天
    useDate.setDate(today.getDate() - Math.floor(Math.random() * 30));
    useDate.setHours(
      Math.floor(Math.random() * 24),
      Math.floor(Math.random() * 60),
      Math.floor(Math.random() * 60)
    );
    
    const orderAmount = generateRandomAmount(30, 150);
    
    records.push({
      id: generateId(),
      linkId,
      customer: randomChoice(customers),
      paymentMethod: randomChoice(paymentMethods),
      amount: orderAmount,
      time: useDate.toISOString(),
      area: randomChoice(areas),
      orderNumber: `ORD-${Date.now().toString().slice(-6)}-${i}`,
      status: 'completed'
    });
  }
  
  // 按时间降序排序
  return records.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime());
}

/**
 * 生成订单管理数据
 * @param count 需要生成的订单数量
 * @returns 订单管理数据数组
 */
export function generateOrdersData(count: number = 30) {
  const statuses = ['pending', 'processing', 'completed', 'cancelled'];
  const paymentMethods = ['PayPal', 'Visa', 'MasterCard', 'UnionPay'];
  const categories = ['汉堡', '炸鸡', '披萨', '面食', '米饭', '沙拉', '甜点', '饮料'];
  const restaurantNames = ['麦当劳', '肯德基', '必胜客', '真功夫', '味千拉面', '星巴克'];
  const customerNames = [
    '张先生', '李女士', '王先生', '刘女士', '陈先生', 
    '杨女士', '赵先生', '周女士', '吴先生', '郑女士'
  ];
  
  return Array(count).fill(0).map((_, index) => {
    // 生成随机创建日期，最远不超过90天
    const orderDate = generateRandomDate(90);
    
    // 随机决定订单包含的商品数量（1-5件）
    const itemCount = Math.floor(Math.random() * 5) + 1;
    
    // 生成订单中的商品
    const items = Array(itemCount).fill(0).map(() => {
      const price = generateRandomAmount(20, 100);
      const discountPrice = price * (1 - Math.random() * 0.3);
      const quantity = Math.floor(Math.random() * 3) + 1;
      const category = randomChoice(categories);
      
      return {
        id: generateId(),
        name: `${randomChoice(['香辣', '原味', '芝士', '黑椒', '烧烤'])}${category}`,
        price,
        discountPrice: +discountPrice.toFixed(2),
        quantity,
        category,
        image: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`,
        subtotal: +(discountPrice * quantity).toFixed(2)
      };
    });
    
    // 计算订单总金额和佣金
    const totalAmount = +items.reduce((sum, item) => sum + item.subtotal, 0).toFixed(2);
    const commissionRate = +(Math.random() * 5 + 15).toFixed(1); // 15%-20%的佣金率
    const commission = +(totalAmount * (commissionRate / 100)).toFixed(2);
    
    // 选择随机状态，但已完成订单的概率更高
    const status = Math.random() > 0.6 ? 'completed' : randomChoice(statuses);
    
    // 生成送达时间（仅针对已完成和配送中的订单）
    let deliveryTime = null;
    if (status === 'completed') {
      const deliveryDate = new Date(orderDate);
      deliveryDate.setMinutes(deliveryDate.getMinutes() + Math.floor(Math.random() * 120) + 30); // 30-150分钟内送达
      deliveryTime = deliveryDate.toISOString();
    } else if (status === 'processing') {
      // 配送中的订单，预计送达时间
      const deliveryDate = new Date();
      deliveryDate.setMinutes(deliveryDate.getMinutes() + Math.floor(Math.random() * 60) + 10); // 10-70分钟内送达
      deliveryTime = deliveryDate.toISOString();
    }
    
    // 生成随机送达地址
    const address = {
      name: randomChoice(customerNames),
      phone: `1${Math.floor(Math.random() * 9 + 1)}${Math.random().toString().slice(2, 11)}`,
      address: `${randomChoice(['北京市', '上海市', '广州市', '深圳市', '杭州市', '成都市'])}${randomChoice(['朝阳区', '海淀区', '东城区', '西城区', '宝安区', '南山区'])}${randomChoice(['星光大道', '科技路', '文化街', '繁华大道', '幸福路'])}${Math.floor(Math.random() * 200) + 1}号`,
      houseNumber: randomChoice(['A座', 'B座', 'C座', '']) + (Math.random() > 0.5 ? `${Math.floor(Math.random() * 20) + 1}层${Math.floor(Math.random() * 10) + 1}号` : '')
    };
    
    return {
      id: generateId(),
      orderNumber: `ORD-${Date.now().toString().slice(-8)}-${index}`,
      createdAt: orderDate,
      status,
      totalAmount,
      commission,
      commissionRate: `${commissionRate}%`,
      paymentMethod: randomChoice(paymentMethods),
      restaurant: {
        id: generateId(),
        name: randomChoice(restaurantNames),
        image: `https://picsum.photos/id/${Math.floor(Math.random() * 50) + 100}/100/100`
      },
      customer: {
        ...address,
        isNewCustomer: Math.random() > 0.7 // 30%概率是新客户
      },
      items,
      itemCount,
      deliveryTime,
      comment: Math.random() > 0.7 ? randomChoice([
        '请尽快送达，谢谢！',
        '不要辣椒，谢谢！',
        '多加点酱料，谢谢！',
        '请帮忙带些餐具，谢谢！',
        '门铃坏了，请打电话'
      ]) : '',
      // 支付链接信息
      paymentLink: {
        id: `LINK-${Date.now().toString().slice(-6)}-${index}`,
        name: `给${randomChoice(['小明', '小红', '小刚', '小丽', '小华', '小张', '小李', '小赵'])}的美食`
      }
    };
  });
}

/**
 * 生成订单详情数据
 * @param orderId 订单ID
 * @returns 订单详情数据
 */
export function generateOrderDetailData(orderId: string) {
  // 从模拟订单数据中找到对应订单
  const allOrders = generateOrdersData(30);
  const order = allOrders.find(o => o.id === orderId) || allOrders[0];
  
  // 订单状态历史
  const statusHistory = [
    {
      status: 'created',
      label: '订单创建',
      time: new Date(order.createdAt).getTime(),
      description: '客户通过您分享的支付链接创建了订单'
    }
  ];
  
  // 如果状态不是待处理，添加支付记录
  if (order.status !== 'pending') {
    const paymentTime = new Date(order.createdAt);
    paymentTime.setMinutes(paymentTime.getMinutes() + Math.floor(Math.random() * 30) + 5);
    
    statusHistory.push({
      status: 'paid',
      label: '支付完成',
      time: paymentTime.getTime(),
      description: `客户通过${order.paymentMethod}完成了支付`
    });
  }
  
  // 如果状态是处理中或已完成，添加订单确认记录
  if (order.status === 'processing' || order.status === 'completed') {
    const confirmTime = new Date(statusHistory[statusHistory.length - 1].time);
    confirmTime.setMinutes(confirmTime.getMinutes() + Math.floor(Math.random() * 10) + 3);
    
    statusHistory.push({
      status: 'processing',
      label: '订单确认',
      time: confirmTime.getTime(),
      description: '餐厅已确认订单并开始准备'
    });
  }
  
  // 如果状态是已完成，添加送达记录
  if (order.status === 'completed') {
    const deliveryTime = new Date(statusHistory[statusHistory.length - 1].time);
    deliveryTime.setMinutes(deliveryTime.getMinutes() + Math.floor(Math.random() * 40) + 20);
    
    statusHistory.push({
      status: 'completed',
      label: '订单完成',
      time: deliveryTime.getTime(),
      description: '订单已送达，交易完成'
    });
  }
  
  // 如果状态是已取消，添加取消记录
  if (order.status === 'cancelled') {
    const cancelTime = new Date(statusHistory[statusHistory.length - 1].time);
    cancelTime.setMinutes(cancelTime.getMinutes() + Math.floor(Math.random() * 60) + 10);
    
    statusHistory.push({
      status: 'cancelled',
      label: '订单取消',
      time: cancelTime.getTime(),
      description: '订单已取消，退款已处理'
    });
  }
  
  // 支付信息
  const paymentInfo = {
    method: order.paymentMethod,
    transactionId: 'TXN' + Math.random().toString(36).substring(2, 10).toUpperCase(),
    paymentTime: statusHistory.find(s => s.status === 'paid')?.time || null,
    amount: order.totalAmount,
    status: order.status === 'pending' ? '待支付' : '已支付'
  };
  
  // 佣金计算
  const commissionCalculation = {
    originalTotal: order.items.reduce((sum, item) => sum + (item.price * item.quantity), 0),
    discountTotal: order.totalAmount,
    discountAmount: order.items.reduce((sum, item) => sum + ((item.price - item.discountPrice) * item.quantity), 0),
    commissionRate: order.commissionRate,
    commissionAmount: order.commission
  };
  
  return {
    id: order.id,
    orderNumber: order.orderNumber,
    status: order.status,
    customer: order.customer,
    restaurant: order.restaurant,
    items: order.items,
    totalAmount: order.totalAmount,
    createdAt: order.createdAt,
    paymentInfo,
    commissionCalculation,
    statusHistory,
    paymentLink: order.paymentLink || null
  };
}

/**
 * 生成佣金明细数据
 * @param params 查询参数（开始日期、结束日期、状态）
 * @returns 佣金明细数据数组
 */
export function generateCommissionDetailsData(params: { startDate?: string; endDate?: string; status?: string } = {}) {
  // 基础数据生成
  const count = 30; // 生成30条记录
  const details = [];
  
  const statuses = ['pending', 'withdrawable', 'withdrawn'];
  const productNames = [
    '香辣鸡腿堡', '双层芝士汉堡', '巨无霸', '麦辣鸡翅', 
    '意式肉酱面', '泰式冬阴功汤', '日式拉面', '韩式石锅拌饭',
    '水果沙拉', '提拉米苏', '黑森林蛋糕', '草莓冰淇淋'
  ];
  
  // 生成基础数据
  for (let i = 0; i < count; i++) {
    // 随机日期（过去180天内）
    const date = new Date();
    date.setDate(date.getDate() - Math.floor(Math.random() * 180));
    const createdAt = date.toISOString();
    
    // 随机金额
    const originalPrice = generateRandomAmount(30, 150);
    const discountPrice = originalPrice * (1 - Math.random() * 0.3);
    const quantity = Math.floor(Math.random() * 3) + 1;
    const salesAmount = +(discountPrice * quantity).toFixed(2);
    
    // 佣金计算（原价与折扣价的差额的一定比例）
    const commissionRate = 0.7; // 70%的佣金率
    const amount = +((originalPrice - discountPrice) * quantity * commissionRate).toFixed(2);
    
    // 随机状态
    const status = randomChoice(statuses);
    
    // 产品信息
    const productName = randomChoice(productNames);
    
    details.push({
      id: generateId(),
      orderNumber: `ORD-${Date.now().toString().slice(-6)}-${i}`,
      productName,
      productImage: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/200/200`,
      originalPrice,
      discountPrice,
      quantity,
      salesAmount,
      amount,
      status,
      createdAt
    });
  }
  
  // 筛选数据
  let filteredDetails = [...details];
  
  // 按日期筛选
  if (params.startDate) {
    const startDate = new Date(params.startDate);
    filteredDetails = filteredDetails.filter(detail => new Date(detail.createdAt) >= startDate);
  }
  
  if (params.endDate) {
    const endDate = new Date(params.endDate);
    endDate.setHours(23, 59, 59, 999); // 设置为当天的最后一毫秒
    filteredDetails = filteredDetails.filter(detail => new Date(detail.createdAt) <= endDate);
  }
  
  // 按状态筛选
  if (params.status) {
    filteredDetails = filteredDetails.filter(detail => detail.status === params.status);
  }
  
  // 按日期排序（降序）
  return filteredDetails.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
}

/**
 * 生成提现记录数据
 * @param params 查询参数（开始日期、结束日期、状态）
 * @returns 提现记录数据数组
 */
export function generateWithdrawalRecordsData(params: { startDate?: string; endDate?: string; status?: string } = {}) {
  // 基础数据生成
  const count = 20; // 生成20条记录
  const records = [];
  
  const statuses = ['pending', 'approved', 'paid', 'rejected'];
  const paymentMethods = ['支付宝', '微信', '银行卡'];
  const rejectReasons = [
    '账户信息不正确',
    '提现金额超出可提现余额',
    '账户存在风险',
    '未通过实名认证',
    '提现金额未达到最低要求'
  ];
  
  // 生成基础数据
  for (let i = 0; i < count; i++) {
    // 随机申请日期（过去一年内）
    const applicationDate = new Date();
    applicationDate.setDate(applicationDate.getDate() - Math.floor(Math.random() * 365));
    
    // 随机金额
    const amount = generateRandomAmount(100, 5000);
    
    // 随机状态
    const status = randomChoice(statuses);
    
    // 支付方式
    const paymentMethod = randomChoice(paymentMethods);
    
    // 到账日期（仅对已通过/已打款状态）
    let paymentDate = null;
    if (status === 'paid' || status === 'approved') {
      const payDate = new Date(applicationDate);
      payDate.setDate(payDate.getDate() + Math.floor(Math.random() * 5) + 1); // 1-5天后
      paymentDate = payDate.toISOString();
    }
    
    // 拒绝原因（仅对已拒绝状态）
    const rejectReason = status === 'rejected' ? randomChoice(rejectReasons) : null;
    
    records.push({
      id: generateId(),
      applicationDate: applicationDate.toISOString(),
      amount,
      paymentMethod,
      status,
      paymentDate,
      rejectReason
    });
  }
  
  // 筛选数据
  let filteredRecords = [...records];
  
  // 按日期筛选
  if (params.startDate) {
    const startDate = new Date(params.startDate);
    filteredRecords = filteredRecords.filter(record => new Date(record.applicationDate) >= startDate);
  }
  
  if (params.endDate) {
    const endDate = new Date(params.endDate);
    endDate.setHours(23, 59, 59, 999); // 设置为当天的最后一毫秒
    filteredRecords = filteredRecords.filter(record => new Date(record.applicationDate) <= endDate);
  }
  
  // 按状态筛选
  if (params.status) {
    filteredRecords = filteredRecords.filter(record => record.status === params.status);
  }
  
  // 按申请日期排序（降序）
  return filteredRecords.sort((a, b) => new Date(b.applicationDate).getTime() - new Date(a.applicationDate).getTime());
}

/**
 * 生成用户个人资料数据
 * @returns 用户个人资料数据
 */
export function generateUserProfileData() {
  return {
    name: '张三',
    email: 'distributor@example.com',
    phone: '13800138000',
    bio: '我是一名专业的食品经销商，专注于高品质食品的分销服务。拥有5年食品配送经验，与多家餐厅建立了良好的合作关系。',
    avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
    role: '分销商',
    joinDate: '2022-05-15',
    lastLogin: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), // 24小时前
    region: '上海',
    verificationStatus: 'verified',
    twoFactorEnabled: false
  }
}